package com.icesoft.core.dao.criteria;

import java.util.LinkedHashMap;
import java.util.Map;

public class OrderBuilder extends BaseBuilder {

    OrderBuilder(FromBuilder fromBuilder) {
        super(fromBuilder);
    }

    LinkedHashMap<String, Sequence> orders = new LinkedHashMap<>(5);

    OrderBuilder copy(FromBuilder fromBuilder) {
        OrderBuilder orderBuilder = new OrderBuilder(fromBuilder);
        orderBuilder.orders.putAll(orders);
        return orderBuilder;
    }

    public OrderBuilder orderBy(String propertyName, Sequence sequence) {
        propertyName = fromBuilder.appendNickName(propertyName);
        orders.put(propertyName, sequence);
        return this;
    }

    public OrderBuilder desc(String propertyName) {
        return orderBy(propertyName, Sequence.DESC);
    }

    public OrderBuilder asc(String propertyName) {
        return orderBy(propertyName, Sequence.ASC);
    }

    public OrderBuilder descNullLast(String name) {
        return orderBy(name, Sequence.DESC_NULL_LAST);
    }

    public OrderBuilder descNullFirst(String name) {
        return orderBy(name, Sequence.DESC_NULL_FIRST);
    }

    public OrderBuilder ascNullLast(String name) {
        return orderBy(name, Sequence.ASC_NULL_LAST);
    }

    public OrderBuilder ascNullFirst(String name) {
        return orderBy(name, Sequence.ASC_NULL_FIRST);
    }

    public boolean isEmpty() {
        return orders.isEmpty();
    }

    public boolean isContain(String propertyName) {
        return orders.containsKey(propertyName);
    }

    public int size() {
        return orders.size();
    }

    public String getHql() {
        if (orders.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder("order by ");
        for (Map.Entry<String, Sequence> entry : orders.entrySet()) {
            sb.append(entry.getKey()).append(" ").append(entry.getValue().getValue()).append(",");
        }
        sb.setLength(sb.length() - 1);
        return sb.toString();
    }

    @Override
    public String toString() {
        return getHql();
    }
}
